/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xuexiang.xuidemo.slice;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.AttrHelper;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.PageSlider;
import ohos.agp.components.element.ShapeElement;
import ohos.app.Context;

import com.xuexiang.xui_lib.component.banner.transform.PageTransformer;
import com.xuexiang.xui_lib.util.Log;
import com.xuexiang.xuidemo.ResourceTable;
import com.xuexiang.xuidemo.provider.DemoDataProvider;
import com.xuexiang.xuidemo.provider.PageProvider;
import com.xuexiang.xuidemo.util.RuntimePermissionUtil;
import com.xuexiang.xuidemo.view.CollPageSlide;

/**
 * 欢迎页面
 *
 * @since 2021-03-24
 */
public class SplashScreenAbilitySlice extends AbilitySlice {
    private static final String TAG = "SplashScreenAbilitySlice";
    private static final float MIN_SCALE = 0.75f;
    private static final String[] REQUESTBASICPERMISSIONS = {"ohos.permission.READ_USER_STORAGE",
        "ohos.permission.WRITE_USER_STORAGE"};
    private static final int ONEZEROZERO = 100;
    private static final int TWOZERO = 20;
    private static final float ZEROTWO = 0.2f;
    private static final int COLORFF = 0xff;
    private static final int TWO = 2;
    private static final int THREE = 3;
    private static final float SCALE_1_5 = 1.5F;
    private static final int DURATION_TIME = 300;
    private static final int MARGIN10 = 10;
    private static final int MARGIN20 = 20;
    private static final int IMAGE_SIZE = 8;
    private Context context;
    private CollPageSlide mPageSlider;
    private Button btnStart;
    private DirectionalLayout indicator;
    private Button btnStart1;
    private boolean isViewPagerBanner; // 是否来自ViewPageBanner

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_splash_screen_layout);
        context = this;
        initView();
        initPages();
        setPagerData(intent);
        RuntimePermissionUtil.requestPermission(getAbility(), REQUESTBASICPERMISSIONS, ONEZEROZERO);
    }

    /**
     * 从ViewPager页面跳转到启动页 需要对启动页做六种动画
     *
     * @param intent
     */
    private void setPagerData(Intent intent) {
        try {
            isViewPagerBanner = intent.getBooleanParam("ViewPagerBanner", false);
            int position = intent.getIntParam("position", 0);
            Class<? extends PageTransformer> pageTransformer = DemoDataProvider.transformers()[position];
            if (pageTransformer != null) {
                mPageSlider.setPageTransformer(pageTransformer.newInstance());
            }
        } catch (IllegalAccessException e) {
            Log.e(TAG, "setPagerData IllegalAccessException :" + e.getLocalizedMessage());
        } catch (InstantiationException e) {
            Log.e(TAG, "setPagerData InstantiationException :" + e.getLocalizedMessage());
        }
    }

    /**
     * initPages
     */
    private void initPages() {
        mPageSlider = (CollPageSlide) findComponentById(ResourceTable.Id_page_slide);
        PageProvider pageProvider = new PageProvider(getContext());
        mPageSlider.setProvider(pageProvider);
        mPageSlider.setPages(pageProvider.getComponents());
        indicator = (DirectionalLayout) findComponentById(ResourceTable.Id_indicator);
        createIndicator(pageProvider);
        mPageSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int i, float v, int i1) {
            }

            @Override
            public void onPageSlideStateChanged(int i) {
            }

            @Override
            public void onPageChosen(int i) {
                if (i == 0) {
                    btnStart.setVisibility(Component.VISIBLE);
                    btnStart1.setVisibility(Component.HIDE);
                }
                if (i == 1) {
                    btnStart.setVisibility(Component.HIDE);
                    btnStart1.setVisibility(Component.HIDE);
                }
                if (i == TWO) {
                    btnStart.setVisibility(Component.HIDE);
                    btnStart1.setVisibility(Component.HIDE);
                }
                if (i == THREE) {
                    btnStart.setVisibility(Component.HIDE);
                    btnStart1.setVisibility(Component.VISIBLE);
                }
                for (int jj = 0; jj < pageProvider.getCount(); jj++) { // 这里将指示器跟viewPager联动起来
                    Image image = (Image) indicator.getComponentAt(jj);
                    if (jj == i) {
                        // 选中红色并放大1.5倍
                        image.setBackground(getRedShapeElement(COLORFF));
                        AnimatorProperty animatorProperty = image.createAnimatorProperty();
                        animatorProperty.scaleX(SCALE_1_5).scaleY(SCALE_1_5);
                        animatorProperty.setDuration(DURATION_TIME);
                        animatorProperty.start();
                    } else {
                        image.setBackground(getWhiteShapeElement());
                        image.setScale(1.0f, 1.0f);
                    }
                }
            }
        });
    }

    /**
     * 设置红色
     *
     * @param colorff
     * @return 元素对象
     */
    private ShapeElement getRedShapeElement(int colorff) {
        ShapeElement shape = new ShapeElement();
        shape.setCornerRadius(AttrHelper.vp2px(TWOZERO, getContext()));
        shape.setRgbColor(new RgbColor(colorff, 0x00, 0x00)); // 设置颜色,红色
        return shape;
    }

    /**
     * 设置白色
     *
     * @return 元素对象
     */
    private ShapeElement getWhiteShapeElement() {
        ShapeElement shape = new ShapeElement();
        shape.setCornerRadius(AttrHelper.vp2px(TWOZERO, getContext()));
        shape.setRgbColor(new RgbColor(COLORFF, COLORFF, COLORFF)); // 设置颜色白色
        return shape;
    }

    /**
     * 创建指示器
     *
     * @param pageProvider
     */
    private void createIndicator(PageProvider pageProvider) {
        for (int ii = 0; ii < pageProvider.getCount(); ii++) {
            Image image = new Image(getContext());
            image.setMarginsLeftAndRight(MARGIN10, MARGIN10);
            image.setMarginsTopAndBottom(MARGIN20, MARGIN20);
            image.setWidth(AttrHelper.vp2px(IMAGE_SIZE, getContext()));
            image.setHeight(AttrHelper.vp2px(IMAGE_SIZE, getContext()));
            if (ii == 0) {
                image.setBackground(getRedShapeElement(COLORFF));
                image.setScale(SCALE_1_5, SCALE_1_5);
            } else {
                image.setBackground(getWhiteShapeElement());
            }
            indicator.addComponent(image);
        }
    }

    private void initView() {
        btnStart = (Button) findComponentById(ResourceTable.Id_btn_start);
        btnStart1 = (Button) findComponentById(ResourceTable.Id_btn_start1);
        btnStart1.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (!isViewPagerBanner) {
                    Intent intent = new Intent();
                    intent.setOperation(new Intent.OperationBuilder()
                        .withBundleName(getContext().getBundleName())
                        .withAbilityName(LoginAbility.class)
                        .build());
                    startAbility(intent);
                }
                terminateAbility();
            }
        });
        btnStart.setVisibility(Component.VISIBLE);
        btnStart.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (!isViewPagerBanner) {
                    // 开发阶段跳过登录页面
                    boolean isSkipLogin = false; // BuildConfig.DEBUG;
                    Intent intent = new Intent();
                    intent.setOperation(new Intent.OperationBuilder()
                        .withBundleName(getContext().getBundleName())
                        .withAbilityName(isSkipLogin ? MainLoadAbility.class : LoginAbility.class)
                        .build());
                    startAbility(intent);
                }
                terminateAbility();
            }
        });
    }

    /**
     * onResult
     *
     * @param requestCode
     * @param resultIntent
     */
    @Override
    protected void onResult(int requestCode, Intent resultIntent) {
        super.onResult(requestCode, resultIntent);
        if (requestCode == 0) {
            if (resultIntent != null) {
                String value = (String) resultIntent.getParams().getParam("test");
            }
        }
    }

    /**
     * 两次返回键退出App.实现的核心要素：
     * 原理：第一次按下返回键时，弹出提示Toast同时记录当时的时间
     * 如果下一次返回键时间与本次间隔在2s内，则退出App，否则
     * 继续两次时间间隔检测
     * 注意：这里是完全复写onBackPressed方法，不要调用父类的onBackPressed
     * 否则按一下返回键就退出了
     */
    @Override
    protected void onBackPressed() {
        if (isViewPagerBanner) {
            terminateAbility();
        }
    }
}

